package com.yiyahui.project.erp.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.github.pagehelper.PageHelper;
import com.yiyahui.common.utils.DateUtils;
import com.yiyahui.common.utils.StringUtils;
import com.yiyahui.common.utils.sql.SqlUtil;
import com.yiyahui.framework.web.domain.AjaxResult;
import com.yiyahui.framework.web.page.PageDomain;
import com.yiyahui.framework.web.page.TableSupport;
import com.yiyahui.project.erp.domain.*;
import com.yiyahui.project.erp.domain.requestVo.ReturnVo;
import com.yiyahui.project.erp.domain.requestVo.YiyaItemBillingExtend;
import com.yiyahui.project.erp.domain.responseVo.ListMainClosingEntriesVo;
import com.yiyahui.project.erp.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yiyahui.project.erp.mapper.YiyaMainClosingEntriesMapper;
import org.springframework.transaction.annotation.Transactional;


/**
 * 主单结账记录流水Service业务层处理
 * 
 * @author yiyahui
 * @date 2020-06-10
 */
@Service
public class YiyaMainClosingEntriesServiceImpl implements IYiyaMainClosingEntriesService 
{
    @Autowired
    private YiyaMainClosingEntriesMapper yiyaMainClosingEntriesMapper;

    @Autowired
    private IYiyaBillingMainService yiyaBillingMainService;

    @Autowired
    private IYiyaItemBillingService yiyaItemBillingService;

    @Autowired
    private IYiyaClosingWaterRelationService yiyaClosingWaterRelationService;

    @Autowired
    private IYiyaAuditDiscountService yiyaAuditDiscountService;

    @Autowired
    private IYiyaMainClosingEntriesService yiyaMainClosingEntriesService;

    @Autowired
    private IYiyaClosingMethodsService yiyaClosingMethodsService;

    @Autowired
    private IYiyaClinicPersonService yiyaClinicPersonService;

    /**
     * 查询主单结账记录流水
     * 
     * @param id 主单结账记录流水ID
     * @return 主单结账记录流水
     */
    @Override
    public YiyaMainClosingEntries selectYiyaMainClosingEntriesById(Long id)
    {
        return yiyaMainClosingEntriesMapper.selectYiyaMainClosingEntriesById(id);
    }

    /**
     * 查询主单结账记录流水列表
     * 
     * @param yiyaMainClosingEntries 主单结账记录流水
     * @return 主单结账记录流水
     */
    @Override
    public List<YiyaMainClosingEntries> selectYiyaMainClosingEntriesList(YiyaMainClosingEntries yiyaMainClosingEntries)
    {
        return yiyaMainClosingEntriesMapper.selectYiyaMainClosingEntriesList(yiyaMainClosingEntries);
    }

    /**
     * 新增主单结账记录流水
     * 
     * @param yiyaMainClosingEntries 主单结账记录流水
     * @return 结果
     */
    @Override
    public int insertYiyaMainClosingEntries(YiyaMainClosingEntries yiyaMainClosingEntries)
    {
        yiyaMainClosingEntries.setCreateTime(DateUtils.getNowDate());
        return yiyaMainClosingEntriesMapper.insertYiyaMainClosingEntries(yiyaMainClosingEntries);
    }

    /**
     * 修改主单结账记录流水
     * 
     * @param yiyaMainClosingEntries 主单结账记录流水
     * @return 结果
     */
    @Override
    public int updateYiyaMainClosingEntries(YiyaMainClosingEntries yiyaMainClosingEntries)
    {
        yiyaMainClosingEntries.setUpdateTime(DateUtils.getNowDate());
        return yiyaMainClosingEntriesMapper.updateYiyaMainClosingEntries(yiyaMainClosingEntries);
    }

    /**
     * 批量删除主单结账记录流水
     * 
     * @param ids 需要删除的主单结账记录流水ID
     * @return 结果
     */
    @Override
    public int deleteYiyaMainClosingEntriesByIds(Long[] ids)
    {
        return yiyaMainClosingEntriesMapper.deleteYiyaMainClosingEntriesByIds(ids);
    }

    /**
     * 删除主单结账记录流水信息
     * 
     * @param id 主单结账记录流水ID
     * @return 结果
     */
    @Override
    public int deleteYiyaMainClosingEntriesById(Long id)
    {
        return yiyaMainClosingEntriesMapper.deleteYiyaMainClosingEntriesById(id);
    }

    @Transactional(rollbackFor=Exception.class)
    public AjaxResult deleteAll(Long mainClosingEntriesId) {
        if (mainClosingEntriesId != null && mainClosingEntriesId > 0) {
            YiyaMainClosingEntries yiyaMainClosingEntries = yiyaMainClosingEntriesMapper.selectYiyaMainClosingEntriesById(mainClosingEntriesId);
            if (yiyaMainClosingEntries != null) {
                if (yiyaMainClosingEntries.getBillStatus() == 3) { // 已结账 不能删除
                    return AjaxResult.error("账单已结，无法删除");
                } else {
                    YiyaItemBilling yiyaItemBillingRequest = new YiyaItemBilling();
                    yiyaItemBillingRequest.setBillingMainId(yiyaMainClosingEntries.getBillingMainId());
                    List<YiyaItemBilling> yiyaItemBillings = yiyaItemBillingService.selectYiyaItemBillingList(yiyaItemBillingRequest);
                    if (yiyaItemBillings.stream().filter(r -> r.getStatus().equals(0)).collect(Collectors.toList()).size() == yiyaItemBillings.size()) { //全部为新建状态 一次费用没交
                        yiyaMainClosingEntriesMapper.deleteYiyaMainClosingEntriesById(mainClosingEntriesId); // 删除结账记录单
                        yiyaBillingMainService.deleteYiyaBillingMainById(yiyaMainClosingEntries.getBillingMainId());//删除主单
                        yiyaItemBillingService.deleteByIds(yiyaItemBillings.stream().map(YiyaItemBilling::getId).collect(Collectors.toList())); // 删除项目
                        yiyaClosingWaterRelationService.deleteByMainClosingEntriesId(mainClosingEntriesId); // 删除项目流水关联
                        yiyaAuditDiscountService.deleteByBillingMainId(yiyaMainClosingEntries.getBillingMainId());// 删除折扣审核
                    } else { //至少交过一次费用
                        yiyaMainClosingEntriesMapper.deleteYiyaMainClosingEntriesById(mainClosingEntriesId); // 删除结账记录单
                        yiyaClosingWaterRelationService.deleteByMainClosingEntriesId(mainClosingEntriesId); // 删除项目流水关联
                    }
                    return AjaxResult.success();
                }
            } else {
                return AjaxResult.error("此单据不存在");
            }
        } else {
            return AjaxResult.error();
        }
    }

    @Override
    public ReturnVo extendList(YiyaMainClosingEntries yiyaMainClosingEntries) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
        List<YiyaMainClosingEntries> list = yiyaMainClosingEntriesService.selectYiyaMainClosingEntriesList(yiyaMainClosingEntries);
        List<Long> mceIds = list.stream().map(YiyaMainClosingEntries::getId).collect(Collectors.toList());
        List<Long> bmIds = list.stream().map(YiyaMainClosingEntries::getBillingMainId).collect(Collectors.toList());
        List<Long> clinicPersonIds = list.stream().map(YiyaMainClosingEntries::getClinicPersonId).collect(Collectors.toList());
        Map<Long, List<YiyaClosingMethods>> closingMethodsMap = yiyaClosingMethodsService.selectByMainClosingEntriesIds(mceIds).stream().collect(Collectors.groupingBy(YiyaClosingMethods::getMainClosingEntriesId));
        Map<Long, YiyaBillingMain> billingMainMap = yiyaBillingMainService.selectByIds(bmIds).stream().collect(Collectors.toMap(YiyaBillingMain::getId, a -> a, (k1, k2) -> k1));
        Map<Long, List<YiyaItemBillingExtend>> extendMap = yiyaItemBillingService.selectByBillingMainIds(bmIds).stream().collect(Collectors.groupingBy(YiyaItemBillingExtend::getBillingMainId));
        Map<Long, YiyaClinicPerson> yiyaClinicPersonMap = yiyaClinicPersonService.selectByIds(clinicPersonIds).stream().collect(Collectors.toMap(YiyaClinicPerson::getId, a -> a, (k1, k2) -> k1));
        List<ListMainClosingEntriesVo> listMainClosingEntriesVos = new ArrayList<>();
        list.forEach(r -> {
            ListMainClosingEntriesVo listMainClosingEntriesVo = new ListMainClosingEntriesVo();
            listMainClosingEntriesVo.setYiyaMainClosingEntries(r);
            listMainClosingEntriesVo.setYiyaClosingMethods(closingMethodsMap.get(r.getId()));
            listMainClosingEntriesVo.setYiyaBillingMain(billingMainMap.get(r.getBillingMainId()));
            listMainClosingEntriesVo.setYiyaClinicPerson(yiyaClinicPersonMap.get(r.getClinicPersonId()));
            List<YiyaItemBillingExtend> yiyaItemBillingExtends = extendMap.get(r.getBillingMainId());
            if (yiyaItemBillingExtends != null && yiyaItemBillingExtends.size() > 0) {
                yiyaItemBillingExtends.forEach(i -> {
                    YiyaClosingWaterRelation yiyaClosingWaterRelation = yiyaClosingWaterRelationService.selectByMainClosingEntriesIdAndItemBillingId(i.getId(), r.getId());
                    i.setStoredDeductPrice(yiyaClosingWaterRelation != null ? yiyaClosingWaterRelation.getStoredDeductPrice() : BigDecimal.ZERO);
                    i.setThisPay(yiyaClosingWaterRelation != null ? yiyaClosingWaterRelation.getThisPay() : BigDecimal.ZERO);
                });
            }
            listMainClosingEntriesVo.setYiyaItemBillingExtends(yiyaItemBillingExtends);
            listMainClosingEntriesVos.add(listMainClosingEntriesVo);
        });
        ReturnVo returnVo = new ReturnVo();
        returnVo.setListOne(listMainClosingEntriesVos);
        returnVo.setListTwo(list);
        return returnVo;
    }

    @Override
    public List<YiyaMainClosingEntries> selectByBillingMainIds(List<Long> billingMainIds) {
        return yiyaMainClosingEntriesMapper.selectByBillingMainIds(billingMainIds);
    }
}
